<template>
	<view class="search-page">
		<!-- 搜索头部 -->
		<view class="search-header">
			<view class="search-input-box">
				<text class="search-icon">🔍</text>
				<input
					type="text"
					v-model="searchText"
					placeholder="搜索火锅食材、调料"
					@confirm="handleSearch"
				/>
				<text class="clear-icon" @click="clearSearch" v-if="searchText">✕</text>
			</view>
			<text class="cancel-btn" @click="goBack">取消</text>
		</view>

		<!-- 搜索历史和热门搜索 -->
		<view class="search-content" v-if="!searchText">
			<!-- 搜索历史 -->
			<view class="search-section">
				<view class="section-header">
					<text class="section-title">搜索历史</text>
					<text class="clear-history" @click="clearHistory">清空</text>
				</view>
				<view class="tag-list">
					<text
						class="tag"
						v-for="(item, index) in searchHistory"
						:key="index"
						@click="handleTagClick(item)"
					>{{item}}</text>
				</view>
			</view>

			<!-- 热门搜索 -->
			<view class="search-section">
				<view class="section-header">
					<text class="section-title">热门搜索</text>
				</view>
				<view class="tag-list">
					<text
						class="tag"
						v-for="(item, index) in hotSearches"
						:key="index"
						@click="handleTagClick(item)"
					>{{item}}</text>
				</view>
			</view>
		</view>

		<!-- 搜索结果 -->
		<view class="search-results" v-else>
			<!-- 排序和筛选栏 -->
			<view class="filter-bar">
				<view class="sort-options">
					<text 
						v-for="(item, index) in sortOptions" 
						:key="index"
						:class="['sort-item', currentSort === item.value ? 'active' : '']"
						@click="handleSort(item.value)"
					>{{item.label}}</text>
				</view>
				<view class="filter-btn" @click="openFilter">
					<text>筛选</text>
				</view>
			</view>

			<!-- 商品列表 -->
			<view class="result-item" v-for="(item, index) in searchResults" :key="index" @click="goProductDetail(item.id)">
				<image :src="item.logo" mode="aspectFill" class="product-image"></image>
				<view class="product-info">
					<text class="product-name">{{item.name}}</text>
					<text class="product-price">¥{{item.price}}</text>
				</view>
			</view>
			
			<!-- 加载状态提示 -->
			<view class="loading-status" v-if="searchResults.length > 0">
				<text v-if="isLoading">正在加载更多...</text>
				<text v-else-if="!hasMore">已经加载完所有数据了</text>
			</view>

			<!-- 筛选抽屉 -->
			<uni-popup ref="filterPopup" type="right" @change="(e) => showFilter = e.show">
				<view class="filter-drawer">
					<view class="drawer-header">
						<text>筛选</text>
						<text class="close-btn" @click="closeFilter">✕</text>
					</view>
					<scroll-view scroll-y class="drawer-content">
						<!-- 价格区间 -->
						<view class="filter-section">
							<text class="section-title">价格区间</text>
							<view class="price-inputs">
								<input type="number" v-model="filter.priceMin" placeholder="最低价" />
								<text>-</text>
								<input type="number" v-model="filter.priceMax" placeholder="最高价" />
							</view>
						</view>
						
						<!-- 商品分类 -->
						<view class="filter-section">
							<text class="section-title">商品分类</text>
							<view class="category-list">
								<text 
									v-for="(item, index) in categories" 
									:key="index"
									:class="['category-item', filter.category === item.value ? 'active' : '']"
									@click="filter.category = item.value"
								>{{item.label}}</text>
							</view>
						</view>
					</scroll-view>
					<view class="drawer-footer">
						<button class="reset-btn" @click="resetFilter">重置</button>
						<button class="confirm-btn" @click="confirmFilter">确定</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {post} from "../../common/api";
import {onShow,onPullDownRefresh,onReachBottom} from "@dcloudio/uni-app";

const router = useRouter()
const searchText = ref('')
const searchHistory = ref([])
const hotSearches = ref(['火锅底料', '毛肚', '虾滑', '肥牛', '羊肉卷'])
const searchResults = ref([])
const currentPage = ref(1)
const totalPage = ref(1)
const isLoading = ref(false)
const hasMore = ref(true)
const currentSort = ref('')
const showFilter = ref(false)
const filterPopup = ref(null)
const filter = ref({
	priceMin: '',
	priceMax: '',
	category: ''
})
const sortOptions = ref([
	{ label: '综合排序', value: '' },
	{ label: '价格从低到高', value: 'price_asc' },
	{ label: '价格从高到低', value: 'price_desc' }
])
const categories = ref([
	{ label: '全部', value: '' },
	{ label: '火锅底料', value: '火锅底料' },
	{ label: '毛肚', value: '毛肚' },
	{ label: '虾滑', value: '虾滑' },
	{ label: '肥牛', value: '肥牛' },
	{ label: '羊肉卷', value: '羊肉卷' }
])

// 从本地存储获取搜索历史

onReachBottom(async () => {
		if (searchText.value) {
			loadMore()
		}
});
// 模拟搜索商品
const searchProducts = async (isLoadMore = false) => {
	if (isLoading.value) return
	
	try {
		isLoading.value = true
		// 处理筛选参数
		const params = {
			page: currentPage.value,
			keyword: searchText.value,
			sort: currentSort.value
		}
		
		// 添加筛选条件
		if (filter.value.priceMin) {
			params.minPrice = Number(filter.value.priceMin)
		}
		if (filter.value.priceMax) {
			params.maxPrice = Number(filter.value.priceMax)
		}
		if (filter.value.category) {
			params.category = filter.value.category
		}
		
		let res = await post("/product/search", params)
		
		if (res.code === 200) {
			if (isLoadMore) {
				searchResults.value = [...searchResults.value, ...res.data]
			} else {
				searchResults.value = res.data
			}
			totalPage.value = res.data.totalPage
			hasMore.value = currentPage.value < totalPage.value
		}
	} catch (error) {
		console.error('搜索失败:', error)
	} finally {
		isLoading.value = false
	}
}

// 加载更多数据
const loadMore = () => {
	if (!hasMore.value || isLoading.value) return
	currentPage.value++
	searchProducts(true)
}

// 处理搜索
const handleSearch = () => {
	if (!searchText.value.trim()) return
	
	// 重置分页数据
	currentPage.value = 1
	hasMore.value = true
	
	// 添加到搜索历史
	if (!searchHistory.value.includes(searchText.value)) {
		searchHistory.value.unshift(searchText.value)
		if (searchHistory.value.length > 10) {
			searchHistory.value.pop()
		}
		uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value))
	}
	
	searchProducts()
}

// 清空搜索
const clearSearch = () => {
	searchText.value = ''
}

// 清空历史
const clearHistory = () => {
	searchHistory.value = []
	uni.removeStorageSync('searchHistory')
}

// 点击标签
const handleTagClick = (keyword) => {
	searchText.value = keyword
	handleSearch()
}

// 返回上一页
const goBack = () => {
	router.back()
}

// 处理排序
const handleSort = (value) => {
	currentSort.value = value
	searchProducts()
}

// 处理筛选
const resetFilter = () => {
	filter.value = {
		priceMin: '',
		priceMax: '',
		category: ''
	}
	currentPage.value = 1
	hasMore.value = true
	searchProducts()
}

const confirmFilter = () => {
	showFilter.value = false
	currentPage.value = 1
	hasMore.value = true
	searchProducts()
}

// 打开筛选抽屉
const openFilter = () => {
	filterPopup.value.open()
}

// 关闭筛选抽屉
const closeFilter = () => {
	filterPopup.value.close()
}

const goProductDetail = (id) => {
	uni.navigateTo({
		url: `/pages/product/detail?id=${id}`
	})
}

</script>

<style>
.search-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.search-header {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #D02B29;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
}

.search-input-box {
	flex: 1;
	display: flex;
	align-items: center;
	background-color: #FFFFFF;
	border-radius: 50rpx;
	padding: 10rpx 20rpx;
	margin-right: 20rpx;
}

.search-icon {
	margin-right: 10rpx;
}

.search-input-box input {
	flex: 1;
	font-size: 28rpx;
}

.clear-icon {
	padding: 0 10rpx;
	color: #999;
}

.cancel-btn {
	color: #FFFFFF;
	font-size: 28rpx;
}

.search-content {
	padding: 30rpx;
	margin-top: 88rpx; /* 为固定搜索栏留出空间 */
}

.search-section {
	margin-bottom: 40rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.clear-history {
	font-size: 28rpx;
	color: #999;
}

.tag-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.tag {
	padding: 10rpx 30rpx;
	background-color: #FFFFFF;
	border-radius: 30rpx;
	font-size: 26rpx;
	color: #666;
}

.search-results {
	padding: 20rpx;
	margin-top: 176rpx; /* 为固定搜索栏和筛选栏留出空间 */
}

.result-item {
	display: flex;
	padding: 20rpx;
	background-color: #FFFFFF;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
}

.product-image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 8rpx;
	margin-right: 20rpx;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 28rpx;
	color: #333;
}

.product-price {
	font-size: 32rpx;
	color: #D02B29;
	font-weight: bold;
}

.loading-status {
	text-align: center;
	padding: 20rpx;
	color: #999;
	font-size: 24rpx;
}

.filter-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background-color: #FFFFFF;
	position: fixed;
	top: 88rpx; /* 搜索栏的高度 */
	left: 0;
	right: 0;
	z-index: 99;
}

.sort-options {
	display: flex;
	gap: 30rpx;
}

.sort-item {
	font-size: 28rpx;
	color: #666;
	position: relative;
}

.sort-item.active {
	color: #D02B29;
}

.sort-item.active::after {
	content: '';
	position: absolute;
	bottom: -4rpx;
	left: 0;
	width: 100%;
	height: 4rpx;
	background-color: #D02B29;
}

.filter-btn {
	font-size: 28rpx;
	color: #666;
	display: flex;
	align-items: center;
}

.filter-btn::after {
	content: '';
	display: inline-block;
	width: 0;
	height: 0;
	border-left: 8rpx solid transparent;
	border-right: 8rpx solid transparent;
	border-top: 8rpx solid #666;
	margin-left: 4rpx;
}

/* 抽屉样式 */
.filter-drawer {
	width: 80vw;
	height: 100vh;
	background-color: #FFFFFF;
	display: flex;
	flex-direction: column;
	z-index: 101; /* 确保抽屉在最上层 */
}

.drawer-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1px solid #eee;
	font-size: 32rpx;
	font-weight: bold;
}

.drawer-content {
	flex: 1;
	padding: 30rpx;
}

.drawer-footer {
	padding: 30rpx;
	border-top: 1px solid #eee;
	display: flex;
	gap: 20rpx;
}

.drawer-footer button {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.filter-section {
	margin-bottom: 30rpx;
}

.price-inputs {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.price-inputs input {
	width: 200rpx;
	height: 60rpx;
	border: 1px solid #eee;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
}

.category-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.category-item {
	padding: 10rpx 30rpx;
	background-color: #f5f5f5;
	border-radius: 30rpx;
	font-size: 26rpx;
	color: #666;
}

.category-item.active {
	background-color: #D02B29;
	color: #FFFFFF;
}
</style>
